package com.platform.service.impl;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.platform.dao.GoodsQrCodeDao;
import com.platform.entity.GoodsEntity;
import com.platform.service.GoodsQrCodeService;
import com.platform.utils.CharUtil;
import com.platform.utils.Query;
import com.platform.utils.ResourceUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.net.ssl.HttpsURLConnection;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.*;
import java.util.List;

@Service
public class GoodsQrCodeServiceImpl implements GoodsQrCodeService {
    private static Logger logger  = Logger.getLogger(GoodsQrCodeServiceImpl.class);



    @Autowired
    private GoodsQrCodeDao goodsQrCodeDao;
    @Override
    public List<GoodsEntity> queryList(Map<String, Object> map) {
        return goodsQrCodeDao.queryList(map);
    }

    @Override
    public int update(GoodsEntity goods) {
        //插入酒店表一条数据 拿到主键id
        String path= ResourceUtil.getConfigByName("goodsQrCode.imgpath");
//            String path= "F://";
        if (!path.endsWith("/"))
        {
            path += "/";
        }
        String picName="goodsCode-"+CharUtil.getRandomString(8)+".jpg";
        path+= picName;
        //把图片存放到服务器 并拿到二维码图片名
        try {
            createQrCode(new FileOutputStream(new File(path)),"https://www.desmart.com.cn/qcs/mini/index.html?goodsId="+goods.getId(),900,"JPEG");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String domainImageUrl= ResourceUtil.getConfigByName("domain.goodsQrCodeImage.url");
        if (!domainImageUrl.endsWith("/"))
        {
            domainImageUrl += "/";
        }
        String url = domainImageUrl+picName;
        goods.setCodePath(url);

        goodsQrCodeDao.update(goods);
        return 0;
    }

    @Override
    public int queryTotal(Map<String,Object> map) {
        return goodsQrCodeDao.queryTotal(map);
    }


    /*
     * 生成进小程序二维码
     * */
    private static void getQRcode(InputStream inputStream){
        try {
            //从输入流中获取字符串信息
            BufferedImage image = ImageIO.read(inputStream);
            //将图像转换为二进制位图源
            LuminanceSource source = new BufferedImageLuminanceSource(image);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            QRCodeReader reader = new QRCodeReader();
            Result result = null ;
            try {
                result = reader.decode(bitmap);
            } catch (ReaderException e) {
                e.printStackTrace();
            }
            System.out.println(result.getText());
        }catch (Exception e){
            e.printStackTrace();
            logger.error("生成二维码出错");
        }
    }

    public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat) throws Exception{
        //设置二维码纠错级别ＭＡＰ
        Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
        hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);  // 矫错级别
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //创建比特矩阵(位矩阵)的QR码编码的字符串
        BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
        // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
        int matrixWidth = byteMatrix.getWidth();
        BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        Graphics2D graphics = (Graphics2D) image.getGraphics();
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, matrixWidth, matrixWidth);
        // 使用比特矩阵画并保存图像
        graphics.setColor(Color.BLACK);
        for (int i = 0; i < matrixWidth; i++){
            for (int j = 0; j < matrixWidth; j++){
                if (byteMatrix.get(i, j)){
                    graphics.fillRect(i-100, j-100, 1, 1);
                }
            }
        }
        return ImageIO.write(image, imageFormat, outputStream);
    }

    /*
     * 生成进公众号二维码
     * */
    private static String getRQcode(String ticket, String savepath)
    {
        //拿到二维码tiket
        //String ticket=WeChatMpUtils.createForeverTicket(null,"hotelId-"+hotelId);
        //获取服务器存放二维码的路径
        String filepath = null;
        String requestUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=TICKET";
        requestUrl = requestUrl.replace("TICKET", ticket);

        try
        {
            URL url = new URL(requestUrl);
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");

            if (!savepath.endsWith("/"))
            {
                savepath += "/";
            }
            // 将ticket 作为文件名
            filepath = savepath + "MpQrCode-"+ UUID.randomUUID().toString() + ".jpg";

            // 将微信服务器返回的输入流写入文件

            BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
            FileOutputStream fos = new FileOutputStream(new File(filepath));

            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();

            conn.disconnect();
            logger.info("根据ticket换取二维码成功");
        } catch (Exception e)
        {
            filepath = null;
            logger.error("根据ticket换取二维码失败" + e);
        }
        return filepath;
    }
}
